import { useEffect, useCallback, useState } from "react"
import { resetDefaultBehavior } from "@utils"
import { message } from "antd"
import useEvent from "./useEvent"
function useDrag(uploadContainerRef, size, type, preview, crop, setIsModalOpen) {
  const [selectedFile, setSelectedFile] = useState(null)
  const [previewFile, setPreviewFile] = useState({
    type: "",
    url: ""
  })
  /**
   * @description: 检验文件
   * @param {*} files
   * @return {*}
   */
  function checkFile(files) {
    const file = files[0]
    if (!file) {
      message.error("请上传文件")
      return
    }
    if (file.size > size) {
      message.error("文件大小不能超过" + size + "MB")
      return
    }
    if (!type.some(item => file.type.includes(item))) {
      message.error("不支持" + file.type + "文件")
      return
    }
    // 都通过之后，设置选中的文件
    setSelectedFile(file)
  }
  const openCropperModal=()=>{
    if (crop) {
      setIsModalOpen(true)
    }
  }
  // 处理拖拽事件
  const handleDrop = useCallback(e => {
    // 同样阻止默认行为
    resetDefaultBehavior(e)
    // 获取的是File对象组成的数组
    const files = e.dataTransfer.files
    checkFile(files)
    openCropperModal()
  }, [])

  // 监听选中的文件,设置预览url
  useEffect(() => {
    if (!preview || !selectedFile) return
    const url = URL.createObjectURL(selectedFile)
    setPreviewFile({
      type: selectedFile.type,
      url
    })
    // 及时释放url，防止内存泄漏
    return () => URL.revokeObjectURL(url)
  }, [selectedFile])

  const resetFileAndPreviewStatus = () => {
    setSelectedFile(null)
    setPreviewFile({
      type: "",
      url: ""
    })
  }

  // 实现点击上传
  useEffect(() => {
    const uploadContainer = uploadContainerRef.current;

    const handleFileInputChange = (e) => {
      checkFile(e.target.files);

      // ASD移除文件输入框，否则选择完毕之后，选择框还在
      document.body.removeChild(e.target);
      openCropperModal()
    };

    const handleClick = () => {
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.style.display = 'none';

      fileInput.addEventListener('change', handleFileInputChange);

      document.body.appendChild(fileInput);
      fileInput.click();
    };

    uploadContainer.addEventListener('click', handleClick);

    // 清理事件监听器
    return () => {
      uploadContainer.removeEventListener('click', handleClick);
    };
  }, []);

  // 监听拖拽事件
  useEvent(uploadContainerRef, "dragover", resetDefaultBehavior)
  useEvent(uploadContainerRef, "dragenter", resetDefaultBehavior)
  useEvent(uploadContainerRef, "dragleave", resetDefaultBehavior)
  useEvent(uploadContainerRef, "drop", handleDrop)

  return { selectedFile, previewFile,resetFileAndPreviewStatus }
}
export default useDrag
